<template>
  <div class="profile">
    <div class="container py-5">
      <!-- 充值成功提示 -->
      <div class="alert alert-success alert-dismissible fade show mb-4" v-if="rechargeSuccess">
        <i class="bi bi-check-circle-fill me-2"></i>
        充值成功！您的账户已增加 <strong>{{ rechargeAmount }}</strong> 积分。
        <button type="button" class="btn-close" @click="closeRechargeAlert"></button>
      </div>
      
      <!-- 支付成功提示 -->
      <div class="alert alert-success alert-dismissible fade show mb-4" v-if="paymentSuccess">
        <i class="bi bi-check-circle-fill me-2"></i>
        订单支付成功！订单号：<strong>{{ orderNo }}</strong>
        <button type="button" class="btn-close" @click="closePaymentAlert"></button>
      </div>
      
      <!-- 生日更新提示 -->
      <div class="alert alert-success alert-dismissible fade show mb-4" v-if="birthdayUpdated">
        <i class="bi bi-check-circle-fill me-2"></i>
        生日信息更新成功！
        <button type="button" class="btn-close" @click="closeBirthdayAlert"></button>
      </div>
      
      <!-- 性别更新提示 -->
      <div class="alert alert-success alert-dismissible fade show mb-4" v-if="genderUpdated">
        <i class="bi bi-check-circle-fill me-2"></i>
        性别信息更新成功！
        <button type="button" class="btn-close" @click="closeGenderAlert"></button>
      </div>
      
      <!-- 操作失败提示 -->
      <div class="alert alert-danger alert-dismissible fade show mb-4" v-if="errorMessage">
        <i class="bi bi-exclamation-triangle-fill me-2"></i>
        {{ errorMessage }}
        <button type="button" class="btn-close" @click="closeErrorAlert"></button>
      </div>
      
      <div v-if="isLoading" class="text-center my-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2">正在加载用户信息...</p>
      </div>
      
      <div v-else class="row">
        <div class="col-md-4">
          <div class="card">
            <div class="card-body text-center">
              <h5 class="card-title">{{ userDetail.username || username }}</h5>
              
              <!-- 用户积分徽章 -->
              <div class="score-badge mb-3">
                <i class="bi bi-star-fill text-warning me-1"></i>
                <span class="fw-bold">{{ userPoints }} 积分</span>
              </div>
              
              <!-- 用户生日信息 -->
              <div class="user-info mt-3 text-center">
                <div class="d-flex align-items-center justify-content-between">
                  <p class="mb-1"><strong>生日：</strong>{{ formatDateWithShangHaiTZ(userDetail.birthday) || '未设置' }}</p>
                  <button class="btn btn-sm btn-outline-primary" @click="openBirthdayModal">
                    <i class="bi bi-pencil-square"></i> 修改
                  </button>
                </div>
              </div>
              
              <!-- 用户性别信息 -->
              <div class="user-info mt-3 text-center">
                <div class="d-flex align-items-center justify-content-between">
                  <p class="mb-1"><strong>性别：</strong>{{ userDetail.gender ? (userDetail.gender === '男' ? '男' : '女') : '未设置' }}</p>
                  <button class="btn btn-sm btn-outline-primary" @click="openGenderModal">
                    <i class="bi bi-pencil-square"></i> 修改
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 积分卡片 -->
          <div class="mt-3">
            <user-score />
          </div>
        </div>
        <div class="col-md-8">
          <!-- 命理分析卡片 -->
          <div class="card">
            <div class="card-header">
              <h5 class="card-title mb-0">我的命理分析</h5>
            </div>
            <div class="card-body">
              <div class="list-group">
                <a href="#" class="list-group-item list-group-item-action">
                  <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">八字分析</h6>
                    <small class="text-muted">3天前</small>
                  </div>
                  <p class="mb-1">基于您的生辰八字进行的详细分析报告</p>
                </a>
                <a href="#" class="list-group-item list-group-item-action">
                  <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">运势预测</h6>
                    <small class="text-muted">1周前</small>
                  </div>
                  <p class="mb-1">未来三个月的运势预测和建议</p>
                </a>
                <a href="#" class="list-group-item list-group-item-action">
                  <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">性格分析</h6>
                    <small class="text-muted">2周前</small>
                  </div>
                  <p class="mb-1">基于命理的性格特征分析</p>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 生日修改模态框 -->
    <div class="modal fade" id="birthdayModal" tabindex="-1" aria-labelledby="birthdayModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="birthdayModalLabel">修改生日信息</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="updateBirthday">
              <div class="mb-3">
                <label for="birthday" class="form-label">生日信息</label>
                <input 
                  type="datetime-local" 
                  class="form-control" 
                  id="birthday" 
                  v-model="birthdayForm.birthday" 
                  required
                >
                <div class="form-text">请选择您的出生年月日时分，精确到分钟即可（对应上海时区 +8:00）</div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" ref="closeModalBtn">取消</button>
            <button type="button" class="btn btn-primary" @click="updateBirthday" :disabled="isUpdating">
              <span v-if="isUpdating" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
              {{ isUpdating ? '更新中...' : '保存' }}
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 性别修改模态框 -->
    <div class="modal fade" id="genderModal" tabindex="-1" aria-labelledby="genderModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="genderModalLabel">修改性别信息</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="updateGender">
              <div class="mb-3">
                <label class="form-label">性别</label>
                <div class="d-flex">
                  <div class="form-check me-4">
                    <input 
                      class="form-check-input" 
                      type="radio" 
                      name="gender" 
                      id="genderMale" 
                      value="男" 
                      v-model="genderForm.gender"
                    >
                    <label class="form-check-label" for="genderMale">男</label>
                  </div>
                  <div class="form-check">
                    <input 
                      class="form-check-input" 
                      type="radio" 
                      name="gender" 
                      id="genderFemale" 
                      value="女" 
                      v-model="genderForm.gender"
                    >
                    <label class="form-check-label" for="genderFemale">女</label>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" ref="closeGenderModalBtn">取消</button>
            <button type="button" class="btn btn-primary" @click="updateGender" :disabled="isUpdating">
              <span v-if="isUpdating" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
              {{ isUpdating ? '更新中...' : '保存' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '../store/userStore'
import { mapState } from 'pinia'
import UserScore from '../components/UserScore.vue'
import { authService } from '../api'
import { Modal } from 'bootstrap'

export default {
  name: 'Profile',
  components: {
    UserScore
  },
  data() {
    return {
      rechargeSuccess: false,
      rechargeAmount: 0,
      paymentSuccess: false,
      orderNo: '',
      birthdayForm: {
        birthday: ''
      },
      genderForm: {
        gender: '男'
      },
      birthdayUpdated: false,
      genderUpdated: false,
      errorMessage: '',
      isUpdating: false,
      isLoading: true,
      userDetail: {},
      birthdayModal: null,
      genderModal: null
    }
  },
  computed: {
    ...mapState(useUserStore, ['username', 'settings', 'userPoints'])
  },
  async mounted() {
    // 检查URL参数是否包含充值成功信息
    const { rechargeSuccess, amount, paymentSuccess, orderNo } = this.$route.query;
    
    if (rechargeSuccess === 'true' && amount) {
      this.rechargeSuccess = true;
      this.rechargeAmount = amount;
    }
    
    if (paymentSuccess === 'true' && orderNo) {
      this.paymentSuccess = true;
      this.orderNo = orderNo;
      
      // 成功支付后刷新用户积分信息
      const userStore = useUserStore();
      userStore.getUserScore();
    }
    
    // 清除URL参数，但不刷新页面
    this.$router.replace({ path: this.$route.path });
    
    // 获取用户详情信息
    await this.fetchUserDetail();
    
    // 初始化Bootstrap模态框
    this.initModal();
  },
  methods: {
    initModal() {
      // 初始化生日Bootstrap模态框
      const birthdayModalEl = document.getElementById('birthdayModal');
      if (birthdayModalEl) {
        this.birthdayModal = new Modal(birthdayModalEl);
        
        // 监听模态框关闭事件，清除可能的错误信息
        birthdayModalEl.addEventListener('hidden.bs.modal', () => {
          this.errorMessage = '';
        });
      }
      
      // 初始化性别Bootstrap模态框
      const genderModalEl = document.getElementById('genderModal');
      if (genderModalEl) {
        this.genderModal = new Modal(genderModalEl);
        
        // 监听模态框关闭事件，清除可能的错误信息
        genderModalEl.addEventListener('hidden.bs.modal', () => {
          this.errorMessage = '';
        });
      }
    },
    openBirthdayModal() {
      // 在打开模态框前，确保生日表单使用当前显示的生日
      this.setBirthdayFromUserDetail();
      
      if (this.birthdayModal) {
        this.birthdayModal.show();
      }
    },
    closeBirthdayModal() {
      if (this.birthdayModal) {
        this.birthdayModal.hide();
      }
    },
    openGenderModal() {
      // 在打开模态框前，确保性别表单使用当前显示的性别
      this.setGenderFromUserDetail();
      
      if (this.genderModal) {
        this.genderModal.show();
      }
    },
    closeGenderModal() {
      if (this.genderModal) {
        this.genderModal.hide();
      }
    },
    setGenderFromUserDetail() {
      // 如果用户有性别信息，将其设置到表单中
      if (this.userDetail.gender) {
        this.genderForm.gender = this.userDetail.gender;
        console.log('性别表单已设置:', this.genderForm.gender);
      } else {
        // 默认设置为男性
        console.log('用户没有性别信息，使用默认值');
        this.genderForm.gender = '男';
      }
    },
    async fetchUserDetail() {
      try {
        this.isLoading = true;
        this.errorMessage = '';
        
        // 调用API获取用户详情
        const result = await authService.getUserDetail();
        
        if (result.success) {
          this.userDetail = result.data || {};
          console.log('获取用户详情成功:', this.userDetail);
          
          // 确保生日表单使用用户实际的生日信息
          this.setBirthdayFromUserDetail();
        } else {
          this.errorMessage = result.message || '获取用户详情失败，请稍后重试';
          console.error('获取用户详情失败:', result);
          
          // 默认设置为当前时间（上海时区）
          this.birthdayForm.birthday = this.getShangHaiTime().slice(0, 16);
        }
      } catch (error) {
        this.errorMessage = '获取用户详情失败，请稍后重试';
        console.error('获取用户详情出错:', error);
        
        // 默认设置为当前时间（上海时区）
        this.birthdayForm.birthday = this.getShangHaiTime().slice(0, 16);
      } finally {
        this.isLoading = false;
      }
    },
    setBirthdayFromUserDetail() {
      // 如果用户有生日信息，将其设置到表单中
      if (this.userDetail.birthday) {
        try {
          // 将ISO格式的生日转换为datetime-local的格式，确保使用上海时区
          const birthdayInShangHaiTZ = this.convertToShangHaiTimezone(this.userDetail.birthday);
          
          if (birthdayInShangHaiTZ) {
            // 转换为YYYY-MM-DDThh:mm格式
            this.birthdayForm.birthday = birthdayInShangHaiTZ.slice(0, 16);
            console.log('生日表单已设置为上海时区:', this.birthdayForm.birthday);
          } else {
            console.error('无效的生日日期:', this.userDetail.birthday);
            // 默认设置为当前时间（上海时区）
            this.birthdayForm.birthday = this.getShangHaiTime().slice(0, 16);
          }
        } catch (error) {
          console.error('设置生日表单时出错:', error);
          // 默认设置为当前时间（上海时区）
          this.birthdayForm.birthday = this.getShangHaiTime().slice(0, 16);
        }
      } else {
        // 默认设置为当前时间（上海时区）
        console.log('用户没有生日信息，使用当前上海时间');
        this.birthdayForm.birthday = this.getShangHaiTime().slice(0, 16);
      }
    },
    convertToShangHaiTimezone(dateString) {
      if (!dateString) return '';
      
      try {
        // 创建日期对象
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return ''; // 无效日期
        
        // 获取上海时区的日期字符串
        const options = { timeZone: 'Asia/Shanghai' };
        const shangHaiDate = new Date(date.toLocaleString('en-US', options));
        
        // 确保生成的ISOString始终是上海时区的表示
        return shangHaiDate.toISOString();
      } catch (e) {
        console.error('转换上海时区错误:', e);
        return '';
      }
    },
    getShangHaiTime() {
      // 获取当前上海时间的ISO字符串
      const now = new Date();
      const options = { timeZone: 'Asia/Shanghai' };
      const shangHaiNow = new Date(now.toLocaleString('en-US', options));
      return shangHaiNow.toISOString();
    },
    formatDateWithShangHaiTZ(dateString) {
      if (!dateString) return '';
      
      try {
        // 创建日期对象
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return ''; // 无效日期
        
        // 使用上海时区获取日期时间信息
        const options = { timeZone: 'Asia/Shanghai' };
        const shangHaiDate = new Date(date.toLocaleString('en-US', options));
        
        // 提取年月日时分并格式化为中文格式
        const year = shangHaiDate.getFullYear();
        const month = String(shangHaiDate.getMonth() + 1).padStart(2, '0');
        const day = String(shangHaiDate.getDate()).padStart(2, '0');
        const hour = String(shangHaiDate.getHours()).padStart(2, '0');
        const minute = String(shangHaiDate.getMinutes()).padStart(2, '0');
        
        // 返回中文格式的日期时间
        return `${year}年${month}月${day}日 ${hour}时${minute}分`;
      } catch (e) {
        console.error('日期格式化错误:', e);
        return dateString; // 返回原始字符串
      }
    },
    updateSettings() {
      const userStore = useUserStore()
      userStore.updateSettings(this.settings)
      console.log('更新设置:', this.settings)
    },
    closeRechargeAlert() {
      this.rechargeSuccess = false;
    },
    closePaymentAlert() {
      this.paymentSuccess = false;
    },
    closeBirthdayAlert() {
      this.birthdayUpdated = false;
    },
    closeGenderAlert() {
      this.genderUpdated = false;
    },
    closeErrorAlert() {
      this.errorMessage = '';
    },
    async updateBirthday() {
      try {
        this.isUpdating = true;
        this.errorMessage = '';
        this.birthdayUpdated = false;
        
        // 确保生日格式正确
        const birthday = this.birthdayForm.birthday;
        if (!birthday) {
          this.errorMessage = '请选择生日日期';
          return;
        }
        
        // 转换为ISO格式，确保是上海时区
        const localDate = new Date(birthday);
        
        // 将本地日期时间转换为上海时区的ISO字符串，只保留年月日时分
        // 创建一个表示相同日期但明确指定为上海时区的日期对象
        const shanghaiDateStr = `${localDate.getFullYear()}-${
          String(localDate.getMonth() + 1).padStart(2, '0')}-${
          String(localDate.getDate()).padStart(2, '0')}T${
          String(localDate.getHours()).padStart(2, '0')}:${
          String(localDate.getMinutes()).padStart(2, '0')}:00+08:00`;
        
        console.log('发送到服务器的上海时区日期:', shanghaiDateStr);
        
        // 调用API更新生日
        const result = await authService.updateBirthday(shanghaiDateStr);
        
        if (result.success) {
          this.birthdayUpdated = true;
          console.log('生日更新成功:', result);
          
          // 关闭模态框
          this.closeBirthdayModal();
          
          // 重新获取用户详情，刷新页面数据
          await this.fetchUserDetail();
        } else {
          this.errorMessage = result.message || '生日更新失败，请稍后重试';
          console.error('生日更新失败:', result);
        }
      } catch (error) {
        this.errorMessage = '操作失败，请稍后重试';
        console.error('更新生日出错:', error);
      } finally {
        this.isUpdating = false;
      }
    },
    
    async updateGender() {
      try {
        this.isUpdating = true;
        this.errorMessage = '';
        this.genderUpdated = false;
        
        // 确保性别值存在
        const gender = this.genderForm.gender;
        if (!gender) {
          this.errorMessage = '请选择性别';
          return;
        }
        
        console.log('发送到服务器的性别:', gender);
        
        // 调用API更新性别
        const result = await authService.updateGender(gender);
        
        if (result.success) {
          this.genderUpdated = true;
          console.log('性别更新成功:', result);
          
          // 关闭模态框
          this.closeGenderModal();
          
          // 重新获取用户详情，刷新页面数据
          await this.fetchUserDetail();
        } else {
          this.errorMessage = result.message || '性别更新失败，请稍后重试';
          console.error('性别更新失败:', result);
        }
      } catch (error) {
        this.errorMessage = '操作失败，请稍后重试';
        console.error('更新性别出错:', error);
      } finally {
        this.isUpdating = false;
      }
    }
  }
}
</script>

<style scoped>
.profile .card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.list-group-item:hover {
  background-color: #f8f9fa;
}

.score-badge {
  display: inline-block;
  background-color: #f8f9fa;
  padding: 0.5rem 1rem;
  border-radius: 1rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.user-info {
  background-color: #f8f9fa;
  padding: 1rem;
  border-radius: 0.5rem;
}
</style>